package com.ruoyi.common.validator;

import com.ruoyi.common.exception.GlobalException;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Set;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ValidatorUtils {
    private static final Logger log = LoggerFactory.getLogger(ValidatorUtils.class);
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public ValidatorUtils() {
        throw new IllegalStateException("不允许创建");
    }

    public static void validateEntity(Object object, Class<?>... groups) throws GlobalException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            List<String> errorList = Lists.newArrayList();

            for(ConstraintViolation<Object> constraint : constraintViolations) {
                errorList.add(constraint.getMessage());
            }

            String message = Joiner.on("<br/>").join(errorList);
            log.error(message);
            throw new GlobalException(message);
        }
    }
}